import React from 'react';
import ReactDOM from 'react-dom';
import { Link } from 'react-router-dom';
import { logout } from '../api/auth';
import $ from 'jquery';
import { baseUrl } from '../js/tajax';
import isLogin from '../api/auth';

class AppBar extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLogin: false
        };
    }

    componentDidMount() {
        if (isLogin()) {
            let token = localStorage.getItem('Token');
            $.ajax({
                url: baseUrl + '/auth/valid/' + token,
                method: 'get',
                success: (data) => {
                    if (data.code === 0) {
                        this.setState({
                            isLogin: true
                        });
                    } else {
                        this.setState({
                            isLogin: false
                        });
                    }
                },
                error: (data) => {
                    this.setState({
                        isLogin: false
                    });
                }
            });
        }
    }


    render() {

        return (
            <nav className="navbar navbar-expand-sm bg-dark navbar-dark">
                <Link className="navbar-brand" to="/">饿了团</Link>
                <ul className="navbar-nav" style={{ position: 'absolute', right: '10px' }}>
                    <LoginControl login={this.state.isLogin} />

                </ul>
            </nav>
        );
    }
}

function LoginControl(props) {
    if (props.login == true) {
        const displayName = localStorage.getItem('displayName');
        return (
            <span className="navbar-text" style={{ color: 'white' }}>
                <div id="appbar-user-info">欢迎，{displayName}。<a href="#" onClick={() => { logout() }}>点击注销</a></div>
            </span>
        );
    } else {
        return (
            <li className="nav-item">
                <button className="btn btn-primary" onClick={() => { window.location.href = '/login' }}>登录</button>
                <button className="btn btn-success" onClick={() => { window.location.href = '/register' }}>注册</button>
            </li>
        );
    }
}

export default AppBar;